package net.imagine.backend.mockrmi.remote.client;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import net.imagine.backend.mockrmi.remote.protocol.RequestBean;
import net.imagine.backend.mockrmi.remote.protocol.ResponseBean;


public class ClientInvocationHandler implements InvocationHandler {
	private final String domain;
	private final int port;
	private final String id;
	private final RequestSender sender;

	public ClientInvocationHandler(String domain, int port, String id, RequestSender sender) {
		this.domain = domain;
		this.port = port;
		this.id = id;
		this.sender = sender;
	}

	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		RequestBean req = createSendBean(id, method, args);
		ResponseBean resp = sender.sendRequest(req, domain, port);
		return resp.getReturnValue();
	}

	private RequestBean createSendBean(String id, Method method, Object[] args) {
		RequestBean sendBean = new RequestBean();
		sendBean.setId(id);
		sendBean.setMethodName(method.getName());
		List<Object> params = new ArrayList<Object>();
		if (args != null) {
			for (Object arg : args) {
				params.add(arg);
			}
		}
		sendBean.setParams(params);
		return sendBean;
	}

}
